package cn.ctyun.xstore.s3.client;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Configurable;

/**
 * S3客户端类
 * 参考文档:
 * https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html
 * https://docs.aws.amazon.com/AmazonS3/latest/API/archive.html
 * 参考代码：https://github.com/awsdocs/aws-doc-sdk-examples
 */
public final class AwsS3ClientBuilder {




    /**
     * 生成一个通用的 S3 客户端，该客户端使用固定的 AK/SK，可作为全局唯一。
     *
     * @param endPoint
     * @param accessKey
     * @param secretKey
     * @return
     */
    public static AmazonS3 buildAmazonS3Client(String endPoint, String accessKey, String secretKey) {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(endPoint, Regions.CN_NORTH_1.getName());
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(endpointConfiguration)
                .build();
    }

    /**
     * 根据临时ak、sk、token生成s3客户端
     *
     * @param endPoint
     * @param accessKey
     * @param secretKey
     * @param sessionToken
     * @return
     */
    public static AmazonS3 buildSessionCredentialsAmazonS3Client(String endPoint, String accessKey, String secretKey, String sessionToken) {
        BasicSessionCredentials credentials = new BasicSessionCredentials(accessKey, secretKey, sessionToken);
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(endPoint, Regions.CN_NORTH_1.getName());
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(endpointConfiguration)
                .build();
    }

}
